<template>
  <div v-loading="loading" class="list-table">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('年份')" prop="yearS">
        <DatePicker v-model="queryParams.yearS" type="year" value-format="yyyy" :placeholder="$t('开始-年')" />
      </el-form-item>
      <el-form-item :label="$t('至')" prop="yearE" label-width="20">
        <DatePicker v-model="queryParams.yearE" type="year" value-format="yyyy" :placeholder="$t('结束-年')" />
      </el-form-item>
      <el-form-item :label="$t('报告周期')" prop="type">
        <el-select v-model="queryParams.type" value="" :placeholder="$t('报告周期')" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('数据来源')" prop="dataSource">
        <el-select v-model="queryParams.dataSource" value="" :placeholder="$t('数据来源')">
          <el-option
            v-for="dict in dataSourceOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('数据变动')" prop="dataSource">
        <el-checkbox-group v-model="changeGroup" size="mini">
          <el-checkbox-button v-for="change in changeOptions" :key="change" :label="change">{{ change }}</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" type="success" @click="refreshIndicatorHandle">{{ $t("重新计算") }}</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="pcwDataKeysList"
      border
      height="700"
      :span-method="objectSpanMethod"
    >
      <template v-for="(item, index) in baseTit">
        <el-table-column
          v-if="ifs(item.label)"
          :key="item.prop"
          :fixed="index < 2"
          :width="index < 2 ? '220' : '180'"
          :label="$t(item.label)"
          :prop="item.prop"
        >
          <template slot-scope="scope">
            <span v-if="index < 2">
              {{ $t(scope.row[item.prop]) }}
            </span>
            <span v-else-if=" item.prop.indexOf('change_')>=0 || item.prop.indexOf('moMChange_')>=0">
              <!-- {{ scope.row[item.prop+"_"+scope.row.subjectName] }} -->
              <span v-if="scope.row[item.prop+'_'+scope.row.subjectName] " class="alignRight" :title="scope.row[item.prop+'_'+scope.row.subjectName]['tbvTitle']">
                <span v-if="scope.row[item.prop+'_'+scope.row.subjectName]['tbv'] && scope.row[item.prop+'_'+scope.row.subjectName]['tbv'] !== 0">{{ moneyFormat(scope.row[item.prop+'_'+scope.row.subjectName]['tbv']) }}%</span>
                <i v-if="scope.row[item.prop+'_'+scope.row.subjectName]['tbv_icon'] === 'asc'" class="el-icon-top  " style="color:#e74c3c !important;" />
                <i v-else-if="scope.row[item.prop+'_'+scope.row.subjectName]['tbv_icon'] === 'desc'" class="el-icon-bottom  " style="color:#16a085 !important;" />
                <i v-else class="el-icon-zero">-</i>
              </span>
            </span>
            <span v-else class="alignRight">
              <!-- :class="scope.row[item.prop]['riskType']" -->
              <!-- {{ scope.row[item.prop] }} -->

              <span v-if="scope.row[item.prop]">{{ showNumberFormat(scope.row[item.prop]) }}</span>
            </span>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- <div v-for="(report, index) in chartArray" :key="index" class="chart-div" style="margin-top: 20px;">
      <KeyIndicatorsChart ref="KeyIndicatorsChart" :title="$t(report.title)" :x-axis-data="report.xAxisData" :legend-data="report.legendData" :series-array="report.seriesArray" />
    </div> -->

  </div>
</template>

<script>
  import { listGroupPcwDataKeys, refreshIndicator } from '@/api/company/pcw/pcwDataKeys'
  // import { KeyIndicatorsChart } from '@/views/chart'
  const changeOptions = ['环比', '同比']
  // import { KeyIndicatorsChart } from '@/views/chart'
  export default {
    // components: {
    //   KeyIndicatorsChart
    // },
    props: {
      companyId: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        chart: null,
        // X轴坐标线
        xAxisData: [],
        // 详细数据
        seriesArray: [],
        // 所有关键指标
        legendData: [],
        // Y轴数据值
        dataValue: [],
        // 表头展示
        baseTit: [],
        loading: true,
        // 财务数据基础数据集合
        pcwDataKeysList: [],
        // 查询参数
        queryParams: {
          companyId: this.companyId,
          type: undefined,
          dataSource: 'act'
        },
        // 报告类型
        typeOptions: [],
        // 分类
        keyReports: [],
        // 存放keyreport 对应的children
        keyChildren: [],
        // 存放所有得echart得数据
        chartArray: [],
        dataSourceOptions: [],
        changeOptions: changeOptions,
        changeGroup: ['同比']
      }
    },
    watch: {
      companyId: {
        handler(val) {
          if (val) {
            this.queryParams.companyId = val
            this.getList()
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      // 财务数据报告周期
      this.getDicts('financial_type').then(response => {
        this.typeOptions = response.data
      })
      this.getDicts('pcw_data_source').then(response => {
        this.dataSourceOptions = response.data
      })
    },
    mounted() {
      this.getList()
    },
    methods: {
      getList() {
        this.baseTit = []
        this.loading = true
        this.chartArray = []
        this.xAxisData = []
        this.keyReports = []
        listGroupPcwDataKeys(this.queryParams).then(response => {
          this.baseTit = response.data.columns
          this.pcwDataKeysList = response.data.data
          if (this.baseTit && this.baseTit.length > 3) {
            for (let i = 3; i < this.baseTit.length; i++) {
              // X轴坐标赋值
              this.xAxisData.push(this.baseTit[i].label)
            }
            // 将所有分类存放在数组中，有几个分类，就创建几张echarts表
            var rows = []
            this.pcwDataKeysList.forEach(item => {
              if (item.keyReport !== '' && rows.indexOf(item.keyReport) === -1) {
                rows.push(item.keyReport)
              }
            })
            this.keyReports = rows
            this.loading = false
            this.$nextTick(() => {
              this.initChart()
            })
          }
          this.loading = false
        })
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          companyId: this.companyId,
          year: undefined,
          type: undefined,
          attachmentId: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined,
          remark: undefined,
          yearS: undefined,
          yearE: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      queryHandle() {
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
      },
      // 初始化echarts
      initChart() {
        this.chartArray = []
        this.keyReports.forEach(rep => {
          this.seriesArray = []
          this.legendData = []
          this.pcwDataKeysList.forEach(key => {
            this.dataValue = []
            if (key.keyReport === rep) {
              // 遍历获取legendData
              this.legendData.push(key.subjectName)
              // 遍历获取dataValue
              if (this.baseTit.length > 3) {
                for (let i = 3; i < this.baseTit.length; i++) {
                  this.dataValue.push(key[this.baseTit[i].prop].val)
                }
              }
              // console.log(key)
              var series = {
                name: key.subjectName,
                type: 'line',
                statck: '指标值',
                data: this.dataValue,
                smooth: false
              }
              this.seriesArray.push(series)
            }
          })
          const row = {
            title: rep,
            legendData: this.legendData,
            seriesArray: this.seriesArray,
            xAxisData: this.xAxisData
          }
          this.chartArray.push(row)
        })
      },
      refreshIndicatorHandle() {
        this.msgInfo(this.$t('操作成功,后台计算中,请稍候查看'))
        refreshIndicator(this.queryParams.companyId).then(res => {
          if (res.code === 200) {
            this.getList()
          }
        }).catch(() => {
        })
      },
      objectSpanMethod({ rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          const spanArr = this.rowspan()
          for (let i = 0; i < spanArr.length; i++) {
            const _row = spanArr[rowIndex]
            return {
              rowspan: _row,
              colspan: 1
            }
          }
        }
      },
      rowspan() {
        // 二维数组，用于存放单元格合并规则
        const spanArr = []
        // 用于存储相同项的开始index
        let position = 0
        this.pcwDataKeysList.forEach((item, index) => {
          if (index === 0) {
            spanArr.push(1)
            position = 0
          } else {
            if (this.pcwDataKeysList[index].keyReport === this.pcwDataKeysList[index - 1].keyReport) {
              spanArr[position] += 1 // 有相同项
              spanArr.push(0) // 名称相同后往数组里面加一项0
            } else {
              spanArr.push(1) // 同列的前后两行单元格不相同
              position = index
            }
          }
        })
        return spanArr
      },
      ifs(label) {
        if (label.indexOf('变动') >= 0) {
            return this.changeGroup.includes(label.substring(0, 2))
        }
        return true
      },
      showNumberFormat(cell) {
          console.log('cell', cell)
          if (cell) {
              if (cell.keyType === 'ratio') {
                // 百分比格式
                return cell['val'] + '%'
              } else {
                // 展示金额格式
                return this.moneyFormat(cell['val'])
              }
          } else {
            return '-'
          }
      }
    }
  }
</script>
<style scoped>
.el-icon-bottom{
  color:#1abc9c !important;
   font-size: 16px;
}
.el-icon-top {
  color:#e74c3c !important;
  font-size: 16px;
}
</style>

